package com.xtianzhuang.www.exception;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import com.xtianzhuang.www.entity.response.base.BaseResponse;

@ControllerAdvice
public class NoPermissionException {
	@ResponseBody
	@ExceptionHandler(UnauthorizedException.class)
	public BaseResponse handleShiroException(HttpServletRequest request, HttpServletResponse httpServletResponse,
			Exception ex) {
		BaseResponse response = new BaseResponse();
		response.setCode("8888");
		response.setMessage("对不起，你没有该权限");
		if (!isAjax(request)) {
			try {
				WebUtils.toHttp(httpServletResponse).sendRedirect("/web2019/pages/noPermission.action");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return response;
	}

	@ResponseBody
	@ExceptionHandler(AuthorizationException.class)
	public BaseResponse AuthorizationException(HttpServletRequest request, Exception ex) {
		BaseResponse response = new BaseResponse();
		response.setCode("8888");
		response.setMessage("权限认证失败");
		return response;
	}

	private boolean isAjax(HttpServletRequest request) {
		return (request.getHeader("X-Requested-With") != null
				&& "XMLHttpRequest".equals(request.getHeader("X-Requested-With").toString()));
	}
}
